//@Author: cyl
//@File: main.go
//@Time: 2022/06/11 17:02:52
package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

/**
练习：
	使用gotoutine与channel实现一个计算int64随机数各位数和的程序
		1. 开启一个gotoutine循环生成int64类型的随机数，发送到jobChan
		2. 开启24个gotoutine从jobChan中取出随机数计算个位数的和，将结果发送到resultChan
		3. 主gotoutine从resultChan取出结果并打印到终端
*/
type job struct {
	value int64
}
type result struct {
	*job
	sum int64
}

var jobChan = make(chan *job, 100)
var resultChan = make(chan *result, 100)
var wg sync.WaitGroup

func RandomNum(zl chan<- *job) {
	defer wg.Done()
	// 生成int64类型的随机数，发送到jobChan
	for {
		x := rand.Int63()
		newJob := &job{
			value: x,
		}
		zl <- newJob
		time.Sleep(time.Microsecond * 500)
	}
}

func Baodelu(zl <-chan *job, rc chan<- *result) {
	defer wg.Done()
	// jobChan中取出随机数计算个位数的和，将结果发送到resultChan
	for {
		job := <-zl
		sum := int64(0)
		n := job.value
		for n > 0 {
			sum += n % 10
			n = n / 10
		}
		newResult := &result{
			job: job,
			sum: sum,
		}
		rc <- newResult
	}
}

func main() {
	wg.Add(1)
	go RandomNum(jobChan)
	// 开启24个gotoutine
	wg.Add(24)
	for i := 0; i < 24; i++ {
		go Baodelu(jobChan, resultChan)
	}
	// 从resultChan取出结果并打印到终端
	for res := range resultChan {
		fmt.Printf("value=%d, sum=%d\n", res.job.value, res.sum)
	}
}
